package person.tavion.securitydemo.core.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;

@Component
public class MyLoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        HashMap<String, Object> map = new HashMap<>();
        String a = "";
        if(e instanceof BadCredentialsException) {
            a = "密码错误";
        } else if(e instanceof DisabledException) {
            a = "账户被禁用";
        } else if(e instanceof AccountExpiredException) {
            a = "账户已过期";
        } else if(e instanceof LockedException) {
            a = "账户被锁定";
        } else if(e instanceof CredentialsExpiredException) {
            a = "账户凭证过期";
        } else if(e instanceof UsernameNotFoundException) {
            //在springsecurity中UsernameNotFoundException被屏蔽无法使用，用户找不到会抛BadCredentialsException
            a = "账户不存在";
        } else if(e instanceof SessionAuthenticationException) {
            a = "您已在其他设备登录，禁止登录";
        } else {
            a = "未知错误";
        }
        System.out.println(e.getMessage());
        map.put("code", "401");
        map.put("message", "登录失败! " + a);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(map));
    }
}